﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blob_Watcher
{
    public delegate void FoundBlobDelegate(string newBlobUri);

    public class LogParser
    {
        private CloudBlockBlob logFile;
        public LogParser(CloudBlockBlob logFile)
        {
            this.logFile = logFile;
        }

        public void ParseFile(FoundBlobDelegate callback)
        {
            using (Stream stream = logFile.OpenRead())
            {
                // read the log file
                using (StreamReader reader = new StreamReader(stream))
                {
                    string logEntry;
                    while ((logEntry = reader.ReadLine()) != null)
                    {
                        // parse the log entry
                        BlobLogEntry blobLog = new BlobLogEntry(logEntry);

                        //NOTE: PutBlockList is the final write for a large block blob
                        // PutBlob can also be used for small enough blobs, but also presents an overwrite of an existing one
                        if (blobLog.OperationType.Equals("PutBlob") || blobLog.OperationType.Equals("PutBlockList"))
                            callback(blobLog.RequestUrl);
                    }
                }
            }

        }
    }
}
